package com.sf.dlb.controller;


import com.sf.dlb.bean.UserGradeBean;
import com.sf.dlb.bean.UserMessageBean;
import com.sf.dlb.bean.UserFeedbackBean;
import com.sf.dlb.bean.UserRquestBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.TokenEntity;
import com.sf.dlb.service.*;
import com.sf.dlb.utils.*;
import com.sf.dlb.vo.ResultVO;
import io.swagger.models.Model;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.servlet.http.HttpServletRequest;


/**
 * 用户
 * Created by jing.tan on 2018/12/10.
 */
@RestController
@RequestMapping("/v1/user")
public class UserController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserInfoService userInfoService;
    @Autowired
    public UserWalletService userWalletService;
    @Autowired
    public UserFeedbackService userFeedbackService;
    @Autowired
    public UserInvitationService userInvitationService;
    @Autowired
    public UserMessageService userMessageService;
    @Autowired
    public UserGradeService userGradeService;

    /**
     * 注册(正式上线)
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public Object register(@RequestBody UserRquestBean userRquestBean) {
        //判断参数是否合法
        if (null==userRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("register request json === " + GsonUtils.getInstance().toJson(userRquestBean));
        if(StringUtils.isEmpty(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "手机号不能为空");
        }
        if(StringUtils.isEmpty(userRquestBean.getValidationCode())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "验证码不能为空");
        }
        if(StringUtils.isEmpty(userRquestBean.getInviteCode())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "邀请码不能为空");
        }
        ResultVO resultVO=userInfoService.registerUser(userRquestBean);
        logger.info("register response json === " + GsonUtils.getInstance().toJson(resultVO));
//        return ResultVOUtil.error(ResponseConstant.ERROR,"需要注册码才能注册");
        return resultVO;
    }

    /**
     * 4.4.	用户登录
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public Object login(@RequestBody UserRquestBean userRquestBean) {
        if (null==userRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        logger.info("login request json === " + GsonUtils.getInstance().toJson(userRquestBean));
        if(StringUtils.isEmpty(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "手机号不能为空");
        }
        if(StringUtils.isEmpty(userRquestBean.getValidationCode())&&StringUtils.isEmpty(userRquestBean.getLoginPassword())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不能为空");
        }
        //是否被预警-冻结
        if(userInfoService.isFreezeLogin(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "账号已被冻结，请解冻之后再使用");
        }
        //是否被预警-禁止登陆
        if(userInfoService.isWarningForBid(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "账号已被禁止3天，请3天后再使用");
        }
        //是否被登陆错误-冻结
        if(userInfoService.isLoginErrorNumber(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "账号已被冻结，请明日再重试");
        }
        ResultVO resultVO=null;
        //验证码登录
        if(StringUtils.isNotBlank(userRquestBean.getValidationCode())){
            resultVO=userInfoService.loginVerificationCode(userRquestBean);
        }else if(StringUtils.isNotBlank(userRquestBean.getLoginPassword())){
            //密码登录
            resultVO=userInfoService.loginPasswrod(userRquestBean);
        }
        logger.info("login response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 刷新token
     */
    @PostMapping(value = "/refreshToken")
    @ResponseBody
    public Object refreshToken(HttpServletRequest request) {
//        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        ResultVO resultVO=userInfoService.getTokenChekout(request);
        //不是过期的状态，直接返回
        if(resultVO.getCode()!=ResponseConstant.ERROR_TOKEN_OVERDUE){
            return resultVO;
        }
        String token=request.getHeader(global.token_request_header_key);
        token=token.substring(global.token_request_header_value_prefix.length()+1);
        TokenEntity tokenEntity=userInfoService.generaAndSaveToken(token);
        logger.info("refreshToekn response json === " + GsonUtils.getInstance().toJson(tokenEntity));
        return ResultVOUtil.success(tokenEntity);
    }
    /**
     * 获取用户信息
     */
    @PostMapping(value = "/getUser")
    @ResponseBody
    public Object getUser(HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO = userInfoService.findByUserAndToken(tokenEntity);
        logger.info("getUser response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 4.7.	修改用户(加密)
     */
    @PostMapping(value = "/update")
    @ResponseBody
    public Object update(HttpServletRequest request,@RequestBody UserRquestBean userRquestBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==userRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        //设置登入密码时，要求是：8-20位，字母、数字、符号的任意两者组合。
        if(StringUtils.isNotBlank(userRquestBean.getLoginPassword())){
            boolean falg=StringFormatUtils.passwordValidity(userRquestBean.getLoginPassword());
            if(!falg){
                return ResultVOUtil.error(ResponseConstant.ERROR, "密码必须是：8-20位，字母、数字、符号的任意两者组合。");
            }
        }
        logger.info("update request json === " + GsonUtils.getInstance().toJson(userRquestBean));
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO=userInfoService.updateUser(userRquestBean,tokenEntity);
        logger.info("update response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 修改用户头像
     */
    @PostMapping(value = "/photo")
    @ResponseBody
    public Object photo(HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request;
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO=userInfoService.uploadUserPhoto(multipartHttpServletRequest,tokenEntity);
        logger.info("photo response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 4.14.	用户钱包（加密）
     */
    @PostMapping(value = "/wallet")
    @ResponseBody
    public Object wallet(HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO = userWalletService.getUserWallet(tokenEntity.getUserId());
        logger.info("wallet response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }

    /**
     * 4.20.	找回登录密码(加密)
     */
    @PostMapping(value = "/updateLoginPassword")
    @ResponseBody
    public Object updateLoginPassword(@RequestBody UserRquestBean userRquestBean) {
        if (null==userRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不能为空");
        }
        if(StringUtils.isBlank(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "手机号不能为空");
        }
        if(StringUtils.isBlank(userRquestBean.getValidationCode())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "验证码不能为空");
        }
        if(StringUtils.isBlank(userRquestBean.getLoginPassword())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "密码不能为空");
        }
        //是否被冻结
        if(userInfoService.isLoginErrorNumber(userRquestBean.getMobile())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "账号已被冻结，请明日再重试");
        }
        ResultVO resultVO=userInfoService.updateLoginPassword(userRquestBean);

        logger.info("updateLoginPassword response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 4.21.	修改支付密码(加密)
     */
    @PostMapping(value = "/updatePayPassword")
    @ResponseBody
    public Object updatePayPassword(HttpServletRequest request,@RequestBody UserRquestBean userRquestBean) {
        ResultVO tokenResultVO=(ResultVO)request.getAttribute("token");
        if (null==userRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        if(StringUtils.isBlank(userRquestBean.getValidationCode())||
            StringUtils.isBlank(userRquestBean.getPayPassword())||
                StringUtils.isBlank(userRquestBean.getLoginPassword())) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不能为空");
        }
        TokenEntity tokenEntity =(TokenEntity)tokenResultVO.getData();
        ResultVO resultVO=userInfoService.updatePayPassword(userRquestBean,tokenEntity);
        logger.info("updatePayPassword response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户反馈
     *
     * @return
     */
    @PostMapping(value = "/userFeedback")
    @ResponseBody
    public Object userFeedback(@RequestParam("file") MultipartFile[] file, HttpServletRequest request, String contactMobile, String content, Model model) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if(StringUtils.isBlank(content)){
            return ResultVOUtil.error(ResponseConstant.ERROR,"参数不合法");
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        UserFeedbackBean userFeedbackBean=new UserFeedbackBean();
        userFeedbackBean.setContactMobile(contactMobile);
        userFeedbackBean.setContent(content);
        userFeedbackBean.setFile(file);
        userFeedbackBean.setUserId(tokenEntity.getUserId());
        logger.info("userFeedback request  === " + GsonUtils.getInstance().toJson(userFeedbackBean));
        resultVO=userFeedbackService.addUserFeedback(userFeedbackBean);
        logger.info("userFeedback response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户实名认证
     *
     * @return
     */
    @PostMapping(value = "/updateUserRealInfo")
    @ResponseBody
    public Object updateUserRealInfo(UserRquestBean userRquestBean,HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
//      判断参数是否合法
        if(null==userRquestBean){
            return ResultVOUtil.error(ResponseConstant.ERROR,"参数不合法");
        }
        if(StringUtils.isBlank(userRquestBean.getName())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"请输入姓名");
        }
        if(StringUtils.isBlank(userRquestBean.getIdNumber())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"请输入证件号");
        }
        if(null==userRquestBean.getFile()||userRquestBean.getFile().length==0){
            return ResultVOUtil.error(ResponseConstant.ERROR,"请上传证件照");
        }
        if(!RegexUtils.checkIdCard(userRquestBean.getIdNumber())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"证件不合法");
        }
        logger.info("updateUserRealInfo request  === " + GsonUtils.getInstance().toJson(userRquestBean));
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO=userInfoService.updateUserRealInfo(userRquestBean,tokenEntity);
        logger.info("updateUserRealInfo response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户邀请记录
     *
     * @return
     */
    @GetMapping(value = "/invitationList")
    @ResponseBody
    public Object invitationList(HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
//      判断参数是否合法
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO=userInvitationService.invitationList(tokenEntity.getUserId());
        logger.info("invitationList response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户消息列表
     *
     * @return
     */
    @GetMapping(value = "/userMessageList/{type}/{page}/{size}")
    @ResponseBody
    public Object userMessageList(HttpServletRequest request,@PathVariable("type") int type,@PathVariable("page") int page,@PathVariable("size")int size) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        if(page==0){
            page=page+1;//pageHelper从1开始算
        }
        if(size==0){
            size=20;//默认20条
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        resultVO= userMessageService.userMessageList(tokenEntity.getUserId(),type,page,size);
        logger.info("userMessageList response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户消息更新
     *
     * @return
     */
    @PostMapping(value = "/userMessageUpdate")
    @ResponseBody
    public Object userMessageUpdate(HttpServletRequest request,@RequestBody UserMessageBean userMessageBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        if(StringUtils.isEmpty(userMessageBean.getState())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"消息状态不能为空");
        }
        if(StringUtils.isEmpty(userMessageBean.getType())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"消息类型不能为空");
        }
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        userMessageBean.setUserId(tokenEntity.getUserId());
        resultVO= userMessageService.userMessageUpdate(userMessageBean);
        logger.info("userMessageUpdate response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取用户等级列表
     * @return
     */
    @GetMapping(value ="/gradeList")
    @ResponseBody
    public Object gradeList(HttpServletRequest request) {
        String token=request.getHeader(global.token_request_header_key);
        ResultVO resultVO=userInfoService.getTokenChekout(request);
        if(resultVO.getCode().intValue()==200){
            TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
            resultVO= userGradeService.gradeList(tokenEntity.getUserId());
        }else{
            //未登录
            resultVO= userGradeService.gradeList();
        }
        logger.info("gradeList response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取(用户)等级信息
     * /gradeInfo 获取用户等级信息
     * /gradeInfo/{grade} 获取指定等级信息
     * @return
     */
    @GetMapping(value ={"/gradeInfo","/gradeInfo/{grade}"})
    @ResponseBody
    public Object gradeInfo(HttpServletRequest request, @PathVariable(required =false) String grade) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        resultVO= userGradeService.gradeInfo(tokenEntity.getUserId(),grade);
        logger.info("gradeInfo response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 购买等级
     * @return
     */
    @PostMapping(value ="/buyGrade")
    @ResponseBody
    public Object buyGrade(HttpServletRequest request, @RequestBody UserGradeBean userGradeBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("buyGrade request gradeId ={} ",userGradeBean.getGradeId());
        Long gradeId=userGradeBean.getGradeId();
        String payPassword=userGradeBean.getPayPassword();
        if(null==gradeId||gradeId==0){
            return ResultVOUtil.error(ResponseConstant.ERROR,"等级Id不合法");
        }
        if(StringUtils.isBlank(payPassword)){
            return ResultVOUtil.error(ResponseConstant.ERROR,"请输入支付密码");
        }
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        resultVO= userGradeService.buyGrade(tokenEntity.getUserId(),gradeId,payPassword);
        logger.info("buyGrade response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户登出
     */
    @PostMapping(value = "/logout")
    @ResponseBody
    public Object logout(HttpServletRequest request) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        resultVO=userInfoService.logout(tokenEntity.getUserId());
        logger.info("logout response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
}
